package com.api.syh56.shengyunhui.controller;

import com.alibaba.fastjson.JSON;
import com.api.syh56.shengyunhui.common.*;
import com.api.syh56.shengyunhui.entity.*;

import com.api.syh56.shengyunhui.entity.vo.LoginVO;
import com.api.syh56.shengyunhui.mapper.DriverMapper;
import com.api.syh56.shengyunhui.mapper.ShiperMapper;
import com.api.syh56.shengyunhui.mapper.UserMapper;
import com.api.syh56.shengyunhui.service.*;

import com.api.syh56.shengyunhui.util.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wechat.pay.java.service.refund.model.QueryByOutRefundNoRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;


/**
 * 用户
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WayBillService wayBillService;

    @Autowired
    private WithDrawService withDrawService;

    @Autowired
    private RoutesService routesService;

    @Autowired
    private CouponDetService couponDetService;


//    /**
//     * 注册
//     * @param user
//     * @return
//     */
//    @PostMapping("/reg")
//    public CommonResult<User> reg(@RequestBody User user){
//        userService.reg(user);
//        return CommonResult.success(user);
//    }

    /**
     * 获取用户信息
     * @param
     * @return
     */

    @RequestMapping(value = "/getinfo", method = RequestMethod.GET)
    public CommonResult<User> getinfo() {
        String id = BaseUserInfo.get(UserInfoEnu.id.getCode());
        String name = BaseUserInfo.get(UserInfoEnu.name.getCode());
        System.out.println(id);
        System.out.println(name);
        User admin = userMapper.selectById(Long.parseLong(id));
        return CommonResult.success(admin);
    }

    /**
     * 更新用户信息
     * @param nickname
     * @param Avatarurl
     * @return
     */

    @RequestMapping(value = "/updateinfo", method = RequestMethod.POST)
    public CommonResult<User> updateinfo(@RequestParam String nickname,@RequestParam String Avatarurl) {
        Long id = Long.valueOf(BaseUserInfo.get(UserInfoEnu.id.getCode()));
        User userDB = userMapper.selectById(id);
        userDB.setNickName(nickname);
        userDB.setAvatarUrl(Avatarurl);
        userMapper.updateById(userDB);
        return CommonResult.success(userDB);
    }

    /**
     * 发送验证码
     * @param user
     * @return
     */

    @PostMapping("/sendsms")
    public CommonResult<User> sendsms(@RequestBody User user){
        User user1=userService.sendsms(user);
        return CommonResult.success(user1);
    }

    /**
     * 验证码登录
     * @param user
     * @return
     */

    @PostMapping("/login")
    public CommonResult<LoginVO> login(@RequestBody User user){
        CommonResult<LoginVO> loginResult = userService.login(user);
        return loginResult;
    }

    /**
     * 角色选择（1货主 2司机）
     * @param role
     * @return
     */
    @PostMapping("/selectRole")
    public CommonResult<String> selectRole(@RequestParam Short role){
        userService.selectRole(role);
        return CommonResult.success(null);
    }


    /**
     * 更新用户昵称
     * @param nickname
     * @return
     */
    @RequestMapping(value = "/updateNickname", method = RequestMethod.POST)
    public CommonResult<User> updateNickname(@RequestParam String nickname) {
        String id = BaseUserInfo.get(UserInfoEnu.id.getCode());
        User userDB=userMapper.selectById(Long.valueOf(id));
        userDB.setNickName(nickname);
        int status = userMapper.updateById(userDB);
        if(status == 1) return CommonResult.success(userDB);
        else return CommonResult.failed("更新昵称失败");
    }

    /**
     * 更新用户头像
     * @param Avatarurl
     * @return
     */
    @RequestMapping(value = "/updateAvatarurl", method = RequestMethod.POST)
    public CommonResult<User> updateAvatarurl(@RequestParam String Avatarurl) {
        String id = BaseUserInfo.get(UserInfoEnu.id.getCode());
        User userDB = userMapper.selectById(Long.valueOf(id));
        userDB.setAvatarUrl(Avatarurl);
        int status = userMapper.updateById(userDB);
        if(status == 1) return CommonResult.success(userDB);
        else return CommonResult.failed("更新头像失败");
    }


    /**
     * 货主、专线认证
     * @param
     * @return
     */
    @RequestMapping(value = "/authentication", method = RequestMethod.POST)
    public CommonResult<User> authentication(@RequestBody User userdto) {
        userService.authentication(userdto);
        return CommonResult.success(null);
    }

    @GetMapping("getUser")
    public CommonResult<User> getUser(){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.lambda()
                .eq(User::getUserName,"18762039978");
        return CommonResult.success(userService.getOne(userQueryWrapper));
    }

    /**
     * 判断是否认证
     */
    @GetMapping(value = "/isAuthentication")
    public CommonResult<User> isAuthentication() {
        String id = BaseUserInfo.get(UserInfoEnu.id.getCode());
        User userDB=userMapper.selectById(Long.valueOf(id));
        if (!userDB.getRoles().equals(Constants.Role.NONE)){
            return CommonResult.success(userDB);
        }else{
            return CommonResult.success(userDB);
        }
    }

    /**
     * 获取用户身份
     * @param id
     * @return
     */
    @RequestMapping(value = "/whichRole", method = RequestMethod.POST)
    public CommonResult<Short> whichRole(@RequestParam Long id) {
        User user = userService.selectById(id);
        if (Objects.nonNull(user)){
            return CommonResult.success(user.getRoles());
        }else{
            return CommonResult.failed("用户不存在");
        }
    }

    /**
     * 专线收入明细
     */
    @GetMapping(value = "/getWaybillIncome")
    public CommonResult<CommonPage<Waybill>> getIncome(@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                              @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        Page<Waybill> page = new Page<>(pageNum,pageSize);
        Long uid = Long.valueOf(BaseUserInfo.get(UserInfoEnu.id.getCode()));
        QueryWrapper<Waybill> waybillQueryWrapper = new QueryWrapper<>();
        waybillQueryWrapper.lambda()
                .eq(Waybill::getDriverId,uid)
                .eq(Waybill::getWaybillStatus,Constants.WaybillStatus.SETTLED);
        Page<Waybill> waybillPage = wayBillService.page(page, waybillQueryWrapper);
        return CommonResult.success(CommonPage.restPage(waybillPage));
    }

    /**
     * 钱包余额查看
     */
    @GetMapping(value = "/getBalance")
    public CommonResult<User> getBalance() {
        Long id = Long.valueOf(BaseUserInfo.get(UserInfoEnu.id.getCode()));
        User userDB=userMapper.selectById(id);
        return CommonResult.success(userDB);
    }



    /**
     * 语音播报设置
     */
    @RequestMapping(value = "/voiceSetting", method = RequestMethod.POST)
    public CommonResult<User> voiceSetting(@RequestBody User user) {
        Boolean voiceSetting = user.getVoiceSetting();

        Long uid = Long.valueOf(BaseUserInfo.get(UserInfoEnu.id.getCode()));
        User userDB = userService.getById(uid);
        userDB.setVoiceSetting(voiceSetting);
        userService.updateById(userDB);
        return CommonResult.success(userDB);
    }

    /**
     * 获取语音播报设置
     */
    @GetMapping(value = "/getVoiceSetting")
    public CommonResult<User> getVoiceSetting() {
        String id = BaseUserInfo.get(UserInfoEnu.id.getCode());
        User userDB=userMapper.selectById(Long.valueOf(id));
        return CommonResult.success(userDB);
    }

    /**
     * 消息推送设置
     */
    @RequestMapping(value = "/messageSetting", method = RequestMethod.POST)
    public CommonResult<User> messageSetting(@RequestParam Boolean messageSetting) {
        Long uid = Long.valueOf(BaseUserInfo.get(UserInfoEnu.id.getCode()));
        User userDB = userService.getById(uid);
        userDB.setMessageSetting(messageSetting);
        userService.updateById(userDB);
        return CommonResult.success(userDB);
    }


    /**
     * 获取注销条件
     */
    @GetMapping(value = "/getClear")
    public CommonResult<HashSet<String>> getClear() {
        Long uid = Long.valueOf(BaseUserInfo.get(UserInfoEnu.id.getCode()));
        //使用map保存不符合的条件
        HashSet<String> conditionSet = new HashSet<>();

        conditionSet = userService.getClear(uid);

        return CommonResult.success(conditionSet);
    }

    /**
     * 账号清除
     */
    @GetMapping(value = "/clear")
    public CommonResult<String> clear() {
        Long uid = Long.valueOf(BaseUserInfo.get(UserInfoEnu.id.getCode()));

        //使用map保存不符合的条件
//        Map<String, String> map = new HashMap<>();
//        map.put("报价中", null);
//        map.put("未完成", null);
//        map.put("账户余额", null);


        User user = userService.selectById(uid);
        Short roles = user.getRoles();
        QueryWrapper<Waybill> waybillQueryWrapper = new QueryWrapper<>();
        //未结束的订单
        List<Short> filterList = Arrays.asList(Constants.WaybillStatus.AWAIT_QUOTE,
                Constants.WaybillStatus.DEPOSIT_PAID, Constants.WaybillStatus.AWAIT_SETTLEMENT);
        //判断用户身份
        if (Constants.Role.SHIPER.equals(roles)){
            waybillQueryWrapper.lambda()
                    .eq(Waybill::getShiperId, uid)
                    .in(Waybill::getWaybillStatus, filterList);
        }else if (Constants.Role.DRIVER.equals(roles)){
            waybillQueryWrapper.lambda()
                    .eq(Waybill::getDriverId, uid)
                    .in(Waybill::getWaybillStatus, filterList);
        }
        List<Waybill> waybills = wayBillService.list(waybillQueryWrapper);

        if (waybills.size() == 0){
            //判断账户余额是否为0
            if (user.getBalanceAmt().compareTo(BigDecimal.ZERO) == 0){
                userService.removeById(uid);


                QueryWrapper<Routes> routesQueryWrapper = new QueryWrapper<>();
                routesQueryWrapper.lambda().eq(Routes::getUid, uid);
                routesService.remove(routesQueryWrapper);
//                QueryWrapper<CouponDet> couponDetWrapper = new QueryWrapper<>();
//                couponDetWrapper.lambda().eq(CouponDet::getUid, uid);
//                couponDetService.remove(couponDetWrapper);

                return CommonResult.success("注销成功");
            }else {
                return CommonResult.success("注销失败，账户余额不为0");
            }
        }else {
            if (user.getBalanceAmt().compareTo(BigDecimal.ZERO) == 0){
                return CommonResult.success("注销失败，存在未结束的订单");
            }else {
                return CommonResult.success("注销失败，存在未结束的订单，账户余额不为0");
            }
        }

//        //逗号拼接订单id
//        String awaitQuote = "";
//        String unFinish = "";
//        for (Waybill waybill : waybills) {
//            Short w = waybill.getWaybillStatus();
//            if (Constants.WaybillStatus.AWAIT_QUOTE.equals(w)){
//                awaitQuote += waybill.getId() + ",";
//            }else if (Constants.WaybillStatus.DEPOSIT_PAID.equals(w) || Constants.WaybillStatus.AWAIT_SETTLEMENT.equals(w)){
//                unFinish += waybill.getId() + ",";
//            }
//        }
//        map.put("报价中", awaitQuote);
//        map.put("未完成", unFinish);




//        String jsonString = JSON.toJSONString(map);
//        return CommonResult.success(jsonString);
    }

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 绑定registrationId
     * @param registrationId
     * @return
     */
    @GetMapping(value = "/addRegistrationId")
    public CommonResult<String> addRegistrationId(String registrationId) {
        Long uid = Long.valueOf(BaseUserInfo.get(UserInfoEnu.id.getCode()));

        Set<String> keys = redisUtil.keys();
        List<String> list = keys.stream().toList();
        for (String key : list) {
            if (!redisTemplate.type(key).toString().equals("SET")){
                continue;
            }

//            System.out.println(redisTemplate.type(key));
//            System.out.println(redisTemplate.type(registrationId));

            if (redisUtil.isMember(key,registrationId)) {
                redisUtil.remove(key,registrationId);
                System.out.println(key+":"+registrationId+"极光推送已解绑");
            }
        }
        redisUtil.sSet(uid.toString(), registrationId);
        Set<Object> members = redisUtil.members(uid.toString());
        System.out.println(uid+":"+registrationId+"极光推送绑定成功");
        System.out.println(members);

        return CommonResult.success("添加成功");
    }

    /**
     * 解绑registrationId
     */
    @GetMapping(value = "/removeRegistrationId")
    public CommonResult<String> removeRegistrationId(String registrationId) {
        Long uid = Long.valueOf(BaseUserInfo.get(UserInfoEnu.id.getCode()));
//        System.out.println(redisTemplate.type(uid.toString()));
//        System.out.println(redisTemplate.type(registrationId));
        redisUtil.remove(uid.toString(),registrationId);
        System.out.println(uid+":"+registrationId+"极光推送解除绑定");
        return CommonResult.success("解绑成功");
    }








}
